package com.bm.main;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.bm.util.ListenerTrade;
import com.bm.util.RedisUtil;
import com.mysql.fabric.xmlrpc.base.Data;

import redis.clients.jedis.Jedis;

//发布
public class Pub {
	private static Logger logger=LogManager.getLogger(ListenerTrade.class);
	private static int thread_num = 10;
    private static int client_num = 1000;
	
	public static void main(String[] args) throws Exception {
		PubRedis();
	}
	
	
	public static void PubRedis(){
		Date date= new Date();
		//记录发送请求数
		System.out.println(date+"======================");
		ExecutorService exec = Executors.newCachedThreadPool();
		// thread_num个线程可以同时访问
		final Semaphore semp = new Semaphore(thread_num);
		// 模拟client_num个客户端访问
		for (int index = 0; index < client_num; index++) {
			final int NO = index;
			Runnable run = new Runnable() {
				public void run() {
					try {
						// 获取许可
						semp.acquire();

//						System.out.println("Thread并发事情>>>" + NO);

						try {
							pubTest(NO,date);
						} catch (Exception e) {  
							e.printStackTrace();
						}

						semp.release();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			exec.execute(run);
		}
		// 退出线程池
		exec.shutdown();
	}
	
	public static void pubTest(int NO,Date date) {
		Jedis jedis = RedisUtil.getJedis();
		try {
			for (int i = 1; i <= 100; i++) {
				//logger.error("【发布请求数】"+1);
				jedis.publish("Trade", "客户端"+NO+"第"+i+"次");
				jedis.publish("Member", "客户端"+NO+"第"+i+"次");
				jedis.publish("User", "客户端"+NO+"第"+i+"次");
			}
			System.out.println("发布执行时间"+date+"==========发布结束时间"+new Date());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			RedisUtil.returnResource(jedis);
		}
	}
}
